<template>
  <ul class="list">
    <li
      class="item"
      v-for="item of letters"
      :key="item"
      :ref="(elem) => (elements[item] = elem)"
      @click="handleLetterClick"
      @touchstart="start"
      @touchend="end"
      @touchmove="move"
    >
      {{ item }}
    </li>
  </ul>
</template>

<script>
import { onUpdated, ref } from "vue";
export default {
  name: "CityAlphabet",
  props: {
    letters: Array,
  },
  setup(props, context) {
    const { elements, startY } = getStartY();
    // console.log(startY.value,'次数')   初始化，更新部调用

    const { start, end, move, handleLetterClick } = usePointerLogic(
      startY,
      props,
      context
    );

    return { elements, handleLetterClick, start, end, move };
  },
};

function usePointerLogic(startY, props, context) {
  let status = false;
  let timer = null;
  function handleLetterClick(e) {
    const letter = e.target.innerText;
    context.emit("change", letter);
  }
  function start() {
    status = true;
  }

  function end() {
    status = false;
  }
  function move(e) {
    if (status) {
      if (timer) {
        clearTimeout(this.timer);
        timer = null;
      }
      timer = setTimeout(() => {
        const index = Math.floor((e.touches[0].clientY - startY.value - 79) / 20);
        console.log(startY.value)
        console.log(index);
        if (index >= 0 && index < props.letters.length) {
          const letter = props.letters[index];
          context.emit("change", letter);
        }
      }, 8);
    }
  }
  return { start, end, move, handleLetterClick };
}

function getStartY() {
  let startY = ref(0);
  const elements = ref({});
  onUpdated(() => {
    // console.log(elements.value['A'].offsetTop)  更新后调用，一般用于获取值
    startY.value = elements.value["A"].offsetTop;
  });
  return { elements, startY };
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/styles/varibles.styl';

.list {
  width: 0.4rem;
  position: absolute;
  top: 1.58rem;
  right: 0.1rem;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;

  .item {
    line-height: 0.4rem;
    color: $bgColor;
    text-align: center;
    cursor: pointer;
  }
}
</style>